package com.kamloo.stg.activity;

import java.util.HashMap;

import com.kamloo.stg.fragment.TabBookmarks;
import com.kamloo.stg.fragment.TabBus;
import com.kamloo.stg.info.AppConstant;
import com.kamloo.stg.R;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.*;
import android.widget.TabHost.TabContentFactory;

public class MainScreen extends FragmentActivity implements TabHost.OnTabChangeListener {
	
	private TabHost mTabHost;
	private HashMap<String, TabInfo> mapTabInfo = new HashMap<String, TabInfo>();	
	
	//----- CLASS DEF -----
	private class TabInfo 
	{
		private String tag;
        private Class cls;
        private Bundle args;
        private Fragment fragment;
		
        TabInfo(String _tag, Class _cls, Bundle _args) 
        {
        	this.tag = _tag;
	        this.cls = _cls;
	        this.args = _args;
	    }	 
    }
	
	//----- CLASS TAB FACTORY -----
	class TabFactory implements TabContentFactory 
	{
		private final Context mContext;
		
		public TabFactory(Context context)
		{
			mContext = context;
		}
			    
	    public View createTabContent(String tag) {
	        View v = new View(mContext);
	        v.setMinimumWidth(0);
	        v.setMinimumHeight(0);
	        return v;
	    }
	}
	
	//----- CLASS CODE -----
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.main_screen);
		setupTabHost(savedInstanceState);
	}
	
	private void setupTabHost(Bundle args) 
	{		
		mTabHost = (TabHost)findViewById(android.R.id.tabhost);
        mTabHost.setup();
        TabInfo tabInfo = null;
        
        // NOTE: Possibility to add an drawable icon upper the indicator
        // Bus tab        
        this.addTab(this, this.mTabHost.newTabSpec(AppConstant.FRAGMENT_TAB_BUS).setIndicator(createTabView(this, getString(R.string.busTab_DisplayName))), 
        				 ( tabInfo = new TabInfo(AppConstant.FRAGMENT_TAB_BUS, TabBus.class, args)));
        this.mapTabInfo.put(tabInfo.tag, tabInfo);        
        
        // Bookmarks tab
        this.addTab(this, this.mTabHost.newTabSpec(AppConstant.FRAGMENT_TAB_BOOKMARKS).setIndicator(createTabView(this, getString(R.string.bookmarksTab_DisplayName))), 
        				 ( tabInfo = new TabInfo(AppConstant.FRAGMENT_TAB_BOOKMARKS, TabBookmarks.class, args)));
        this.mapTabInfo.put(tabInfo.tag, tabInfo);        
                
        // Alarms tab
        //this.addTab(this, this.mTabHost.newTabSpec(AppConstant.FRAGMENT_TAB_ALARMS).setIndicator(createTabView(this, getString(R.string.alarmsTab_DisplayName))), 
        //				 ( tabInfo = new TabInfo(AppConstant.FRAGMENT_TAB_ALARMS, TabAlarms.class, args)));
        //this.mapTabInfo.put(tabInfo.tag, tabInfo);
        
                        
        // Set the default selected tab
        this.onTabChanged(AppConstant.FRAGMENT_TAB_BUS);   
        this.setUpTabClick();
        mTabHost.setOnTabChangedListener(this);	// this is the listener
	}
	
	private void setUpTabClick() {
		this.mTabHost.getTabWidget().getChildAt(0).setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				onTabChanged(AppConstant.FRAGMENT_TAB_BUS);
			}
		});
		
		this.mTabHost.getTabWidget().getChildAt(1).setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				onTabChanged(AppConstant.FRAGMENT_TAB_BOOKMARKS);
			}
		});
	}
	
	private View createTabView(Context context, String indicator)
	{
		View view = LayoutInflater.from(context).inflate(R.layout.tabs_bg, null);
		TextView tv = (TextView) view.findViewById(R.id.tabsText);
		tv.setText(indicator);		
		return view;
	}
		
 	private void addTab(MainScreen activity, TabHost.TabSpec tabSpec, TabInfo tabInfo) 
	{ 		
		// Attach a Tab view factory to the spec
		tabSpec.setContent(activity.new TabFactory(activity));
        String tag = tabSpec.getTag();

        // Check to see if we already have a fragment for this tab, probably
        // from a previously saved state. If so, deactivate it, because our
        // initial state is that a tab isn't shown.
        tabInfo.fragment = activity.getSupportFragmentManager().findFragmentByTag(tag);
        
        if (tabInfo.fragment != null && !tabInfo.fragment.isDetached()) 
        {
            FragmentTransaction ft = activity.getSupportFragmentManager().beginTransaction();
            ft.detach(tabInfo.fragment);
            ft.commit();
            activity.getSupportFragmentManager().executePendingTransactions();
        }

        mTabHost.addTab(tabSpec);
	}
	
 	
	public void onTabChanged(String tag) 
	{
		// Erase the stack of back action
		clearBackStack();
		
		TabInfo newTab = (TabInfo) this.mapTabInfo.get(tag);
		FragmentTransaction ft = this.getSupportFragmentManager().beginTransaction();

      	// Create the fragment that represent the tabs content
        newTab.fragment = Fragment.instantiate(this, newTab.cls.getName(), newTab.args);                             
                   
        ft.replace(R.id.realtabcontent, newTab.fragment, newTab.tag);
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);	// Smooth feeling        
        
        ft.commit();
        // This line will cause the main thread to execute the transaction immediatly rather than soon as possible
        this.getSupportFragmentManager().executePendingTransactions();        
    }
	
	private void clearBackStack()
	{
		FragmentManager manager = this.getSupportFragmentManager();
		for(int i = 0; i < manager.getBackStackEntryCount(); ++i) 
		{    
			manager.popBackStack();
		}
	}
	

    /*
    public void onAlarmSetFromAlarms(DialogFragment dialog) {
    	DBHelper helper = new DBHelper(this);
    	AlarmConfigDialog alarmConfig = (AlarmConfigDialog) dialog;
    	Alarme alarm = AlarmUtility.getAlarmData(alarmConfig.alarm.getAlarm().getId_horaire(), alarmConfig.alarm.getAlarm().getId(), alarmConfig.dayNames, alarmConfig.selectedDays, helper, true);
    	AlarmUtility.createAlarm(alarm, this);
    	
		int index = (Integer) alarmConfig.source.getTag(R.id.row_position_key);
		alarmConfig.alarm.setAlarm(alarm);
		alarmConfig.alarmsAdapter.edit(index, alarmConfig.alarm);
    	alarmConfig.alarmsAdapter.notifyDataSetChanged();
		
    }
    
    public void onAlarmSetFromBus(DialogFragment dialog) {
    	DBHelper helper = new DBHelper(this);
    	SQLiteDatabase db = helper.getWritableDatabase();
    	AlarmConfigFromBusDialog alarmConfig = (AlarmConfigFromBusDialog) dialog;
    	BusTimeRow row = alarmConfig.row;
    	Alarme alarm = AlarmUtility.getAlarmData(row.getHoraire().getId(), alarmConfig.id_alarme, alarmConfig.dayNames, alarmConfig.selectedDays, helper, alarmConfig.editAlarm);
		AlarmUtility.createAlarm(alarm, this);
		
		final int index = (Integer) alarmConfig.source.getTag(R.id.row_position_key);
		row.setAlarm(alarm);
		alarmConfig.adapter.edit(index, row);
		alarmConfig.adapter.notifyDataSetChanged();
    }
    */
}
